package com.dingwen.treasure.kettle.config;

import com.dingwen.treasure.kettle.base.convert.jackson.BaseEnumDeserializer;
import com.dingwen.treasure.kettle.base.convert.jackson.BaseEnumSerializer;
import com.dingwen.treasure.kettle.base.convert.jackson.SimpleDeserializersWrapper;
import com.dingwen.treasure.kettle.base.enums.BaseEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 　LocalDateTimeSerializerConfig
 * 　@author dingwen
 * 　@date 2022/6/27
 */
@Configuration(proxyBeanMethods = false)
public class JacksonDeserializerAndSerializerConfig {

    /**
     * 格式
     */
    @Value("${String.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;



    /**
     * 指定特定类型进行指定序列化、反序列化
     *
     * @param builder 建设者
     * @return {@link ObjectMapper}
     */
    @Bean
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {

        // 简单转换模型
        SimpleModule simpleModule = new SimpleModule();

        // 反序列化
        SimpleDeserializersWrapper simpleDeserializersWrapper = new SimpleDeserializersWrapper();

        // 枚举序列化
        simpleModule.addSerializer(BaseEnum.class, BaseEnumSerializer.INSTANCE);
        // Long： 序列化（解决雪花ID精度丢失问题）
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        // LocalDateTime 序列化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));

        // 枚举反序列化
        simpleDeserializersWrapper.addDeserializer(BaseEnum.class, BaseEnumDeserializer.INSTANCE);
        // LocalDateTime 反序列化
        simpleDeserializersWrapper.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));

        // 反序列化
        simpleModule.setDeserializers(simpleDeserializersWrapper);

        return builder
                .findModulesViaServiceLoader(Boolean.TRUE)
                .modules(simpleModule)
                .build();

    }

}
